<template>
  <div v-if="!isDetail" class="container">
    <div class="app-container">
      <el-row style="height: 100%;">
        <!-- 左侧部门树 -->
        <el-col :span="6" style="height: 100%; padding-right: 20px;">
          <!-- 搜索框 -->
          <div>
            <el-input
              v-model="searchParams.keyword"
              placeholder="请输入员工名称进行搜索"
              prefix-icon="el-icon-search"
              size="small"
              @input="onSearchByKeyword"
            />
          </div>
          <!-- 部门架构树形展示组件 -->
          <el-tree ref="departmentTreeRef" style="margin-top: 20px;" :data="departmentsTree" :props="defaultProps" node-key="id" :default-expand-all="true" :expand-on-click-node="false" highlight-current empty-text="暂无数据" @node-click="onSearchEmployeeByDpt" />
        </el-col>
        <!-- 右侧员工信息展示表格 -->
        <el-col :span="18" style="height: 100%; padding-left: 20px; border-left: 1px solid #eee;">
          <!-- 顶部操作按钮 -->
          <el-row>
            <!-- 群发通知 -->
            <el-col :span="12">
              <el-button size="middle">群发通知</el-button>
            </el-col>
            <!-- 操作按钮 -->
            <el-col :span="12" style="text-align: right;">
              <!-- 添加员工 -->
              <el-button
                type="primary"
                size="middle"
                @click="$router.push(`/employee/detail?page=${searchParams.page}&last=${Math.ceil((total + 1) / searchParams.pagesize)}`)"
              >添加员工</el-button>
              <!-- 导入员工 -->
              <el-button size="middle" @click="onOpenImportExcel">excel导入</el-button>
              <!-- 导出员工 -->
              <el-button size="middle" @click="onExportEmployee">excel导出</el-button>
            </el-col>
          </el-row>
          <!-- 员工信息展示表格 -->
          <el-table :data="employeeList" :header-cell-style="{ backgroundColor: '#f8f9fa' }" style="margin-top: 20px;">
            <!-- 选择框 -->
            <el-table-column align="center" width="40px">
              <template #header>
                <el-checkbox />
              </template>
              <template>
                <el-checkbox />
              </template>
            </el-table-column>
            <!-- 头像 -->
            <el-table-column label="头像" align="center" width="60px">
              <template #default="{ row }">
                <img v-if="row.staffPhoto" :src="row.staffPhoto" style="width: 30px; border-radius: 50%;">
                <span v-else-if="row.username" class="user-avatar name-avatar">{{ row.username.charAt(0) }}</span>
                <span v-else class="user-avatar name-avatar empty">无</span>
              </template>
            </el-table-column>
            <!-- 姓名 -->
            <el-table-column label="姓名" align="center" prop="username" />
            <!-- 手机号 -->
            <el-table-column label="手机号" prop="mobile" align="center" />
            <!-- 工会 -->
            <el-table-column label="工号" prop="workNumber" align="center" />
            <!-- 聘用形式 -->
            <el-table-column label="聘用形式" align="center">
              <template #default="{ row }">
                {{ row.formOfEmployment === 1 ? "正式" : "非正式" }}
              </template>
            </el-table-column>
            <!-- 部门 -->
            <el-table-column label="部门" prop="departmentName" align="center" />
            <!-- 入职时间 -->
            <el-table-column label="入职时间" prop="timeOfEntry" align="center" />
            <el-table-column label="操作" align="center" width="140px">
              <template #default="{ row }">
                <el-button type="text" @click="$router.push(`/employee/detail?id=${row.id}&page=${searchParams.page}`)">查看</el-button>
                <el-button type="text" @click="onOpenAssignRole(row.id)">角色</el-button>
                <el-button type="text" @click="onDeleteEmployee(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :key="searchParams.page"
            background
            layout="->, total, prev, pager, next"
            :total="total"
            :page-size="searchParams.pagesize"
            :current-page="searchParams.page"
            style="margin-top: 20px"
            @current-change="onChangePage"
          />
        </el-col>
      </el-row>
      <!-- 导入员工信息excel弹窗 -->
      <ImportExcel ref="importExcelRef" @uploadSuccess="onTurnLastPage" />
      <!-- 分配角色弹窗 -->
      <AssignRole ref="assignRoleRef" />
    </div>
  </div>
  <router-view v-else />
</template>

<script>
import { getDepartmentListAPI } from '@/api/department'
import { getEmployeeListAPI, exportEmployeeExcelAPI, deleteEmployeeAPI } from '@/api/employee'
import FileSaver from 'file-saver'

import { transListToTreeData } from '@/utils/index'
import ImportExcel from './components/ImportExcel'
import AssignRole from './components/AssignRole'

export default {
  name: 'Employee',
  components: {
    ImportExcel, // 导入员工信息excel弹窗
    AssignRole // 分配角色弹窗
  },
  data() {
    return {
      // 搜索参数对象
      searchParams: {
        page: 1, // 当前页码
        pagesize: 10, // 每页条数
        keyword: '', // 搜索关键字
        departmentId: null // 部门id
      },
      departmentsTree: [], // 组织架构列表
      // el-tree组件配置项
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      employeeList: [], // 员工列表
      total: 0 // 数据总条数
    }
  },
  computed: {
    isDetail() {
      return this.$route.path.indexOf('detail') !== -1
    }
  },
  async created() {
    if (!this.isDetail) {
      // 从'/employee/detail'页面返回时，需要返回到修改的那条数据所在的页码，新增时跳转到最后一页
      const page = this.$route.query.page
      // 获取组织列表
      await this.getDepartmentList()
      // 判断是否从'/employee/detail'页面返回
      if (!page) {
      // 获取第一页的员工列表
        await this.getEmployeeList()
      } else if (page !== 'last') {
      // 判断是否返回到最后一页
      // 获取指定页码的员工列表
        await this.onChangePage(parseInt(page))
      } else {
      // 获取最后一页的员工列表
        await this.onTurnLastPage()
      }
    }
  },
  methods: {
    // 获取组织列表
    async getDepartmentList() {
      const list = await getDepartmentListAPI()
      // 将对象数组列表转化为树形列表结构
      this.departmentsTree = transListToTreeData(list, 0)
      // 渲染完成后默认选中组织树的根组织
      this.searchParams.departmentId = this.departmentsTree[0].id
      this.$nextTick(() => {
        // 设置当前选中的节点为根节点
        this.$refs.departmentTreeRef.setCurrentKey(this.searchParams.departmentId)
      })
    },
    // 按用户名关键字搜索员工
    onSearchByKeyword() {
      // 重新获取员工列表
      // 防抖处理，单位时间内只执行一次
      // 如果500ms内再次触发，则清理上一个定时器，上个定时器的回调函数不执行
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.searchParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 按部门搜索员工
    onSearchEmployeeByDpt(data) {
      this.searchParams.departmentId = data.id
      // 重新获取员工列表
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeListAPI(this.searchParams)
      this.employeeList = rows
      this.total = total
    },
    // 切换页码
    async onChangePage(page) {
      this.searchParams.page = page
      // 重新获取员工列表
      await this.getEmployeeList()
    },
    // 跳转到新增数据位置
    onTurnLastPage() {
      this.total = this.total + 1
      this.searchParams.page = Math.ceil(this.total / this.searchParams.pagesize)
      // 重新获取员工列表
      this.getEmployeeList()
    },
    // 导出员工excel
    async onExportEmployee() {
      // 提示框
      await this.$confirm('确定要导出员工数据吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 确认导出
      const loading = this.$message({
        type: 'info',
        message: '正在导出...',
        duration: 0 })
      // 发送导出员工请求
      const excel = await exportEmployeeExcelAPI()
      FileSaver.saveAs(excel, '员工数据.xlsx')
      loading.close()
      this.$message({ type: 'success', message: '导出成功!' })
    },
    // 打开导入员工excel弹窗
    onOpenImportExcel() {
      this.$refs.importExcelRef.open()
    },
    // 删除员工
    async onDeleteEmployee(row) {
      // 弹出确认弹窗
      await this.$confirm('您确定要删除该员工吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 发送删除员工请求
      await deleteEmployeeAPI(row.id)
      // 提示删除成功
      this.$message({ type: 'success', message: '删除成功!' })
      // 如果是本页最后一条数据且还有上一页，就跳转上一页，否则直接刷新页面
      if (this.searchParams.page > 1 && this.employeeList.length === 1) {
        // 跳转到上一页
        this.onChangePage(this.searchParams.page - 1)
      } else {
        // 刷新列表
        this.getEmployeeList()
      }
    },
    // 打开分配角色弹窗
    onOpenAssignRole(id) {
      this.$refs.assignRoleRef.open(id)
    }
  }
}
</script>

<style lang="scss" scoped>
  // 头像
  .user-avatar {
    display: inline-block;
    cursor: pointer;
    width: 30px;
    height: 30px;
    border-radius: 50%;
  }

  // 用户名第一个字符做头像
  .name-avatar {
    text-align: center;
    line-height: 30px;
    background-color: #04c9be;
    color: #fff;
    font-size: 16px;
  }

  // 空头像
  .empty {
    background-color: #ccc;
  }
</style>
